<?

namespace App\Servers\WebSocket\Logics;

use App\Servers\WebSocket\abstracts\LogicAbstract;
use App\Servers\WebSocket\Utils\JWT;

class RoomChat extends LogicAbstract
{
    // 发送消息到指定的房间
    public function send($data)
    {
        $roomId = $data->roomId;
        $payload = JWT::decode($data->token);
        if (!$payload) {
            return ['code' => 1000, 'msg' => '发送消息失败，token错误'];
        }
        $userId = $payload['user_id']; // 此处应该是根据套接字获取个人用户id
        $redis = $this->threadTool['redis']->get();
        $redis->zadd('poker_room_chat_id:' . $roomId, time(), json_encode(['user_id' => $userId, 'msg' => $data->msg, 'date' => date("Y-m-d H:i:s")]));
        $obj = new \stdClass();
        $obj->scope = 'chat-room';
        $obj->op = 'list';
        $obj->data = new \stdClass();
        $obj->data->roomId = $roomId;
        $this->threadTool['channel']->push($obj);
        $this->threadTool['redis']->put($redis);
        return ['code' => 1, 'msg' => '发送消息成功'];
    }
    //获取房间聊天记录
    public function list($data)
    {
        $roomId = $data->roomId;
        $redis = $this->threadTool['redis']->get();
        $redis->sadd('record_room_id:' . $roomId.':fds', $this->fd); //记录：将套接字加到对应房间集合
        $data = $redis->zrange('poker_room_chat_id:' . $roomId, 0, 200);
        $this->threadTool['redis']->put($redis);
        return $data;
    }
}